package com.ahy231.service.impl;

import com.ahy231.dto.GetUsers;
import com.ahy231.entity.Friend;
import com.ahy231.mapper.FriendMapper;
import com.ahy231.mapper.UserMapper;
import com.ahy231.service.UserService;
import com.ahy231.utils.ChineseCharToEn;
import com.ahy231.utils.JWTUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.*;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.*;

import java.util.List;

/**
 * @author ahy231
 * @date 2021/8/2 9:07
 * @description
 */
@Service
public class UserServiceImpl implements UserService {

    private final FriendMapper friendMapper;
    private final UserMapper userMapper;

    public UserServiceImpl(FriendMapper friendMapper, UserMapper userMapper) {
        this.friendMapper = friendMapper;
        this.userMapper = userMapper;
    }

    @Override
    public PageInfo<GetUsers> getFriends(Integer pageNum, Integer pageSize) {
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Assert.notNull(pageNum, "pageNum 为空");
        Assert.notNull(pageSize, "pageSize 为空");
        Page<GetUsers> page = PageHelper.startPage(pageNum, pageSize);
        List<GetUsers> friends = friendMapper.getFriends(userId);
        for (GetUsers u :
                friends) {
            String username = u.getUsername();
            String firstLetter = ChineseCharToEn.getFirstLetter(username.substring(0, 1));
            u.setLetter(firstLetter);
        }
        return PageInfo.of(page);
    }

    @Override
    public List<GetUsers> queryFriend(String username) {
        Long userId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        return friendMapper.queryFriend(userId, username);
    }

    @Override
    public List<GetUsers> queryUsers(String username) {
        return StringUtils.hasText(username) ? userMapper.queryUsers(username) : null;
    }

    @Override
    public Boolean add(Long userId) {
        Long selfId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Friend entity = new Friend(selfId, userId);
        boolean friendNotExists = friendMapper.selectOne(new QueryWrapper<>(entity)) == null;
        Assert.isTrue(friendNotExists, "已经添加过该联系人");
        boolean userExists = userMapper.selectById(userId) != null;
        Assert.isTrue(userExists, "用户不存在");
        return friendMapper.insert(entity) == 1;
    }

    @Override
    public Boolean delete(Long userId) {
        Long selfId = getUserId();
        Assert.notNull(userId, "service 获取不到用户 id");
        Friend entity = new Friend(selfId, userId);
        return friendMapper.delete(new QueryWrapper<>(entity)) > 0;
    }

    private Long getUserId() {
        return JWTUtil.getUserId(SecurityUtils.getSubject().getPrincipal().toString());
    }
}
